﻿using System;
using System.Globalization;
using Monkey.Warrenty.Biz;
using Monkey.Warrenty.Constants;
using Monkey.Warrenty.EntityModel;
using MonkeyWarranty.Web.Common;

namespace MonkeyWarranty.Web.WarrantyTickets
{
    public partial class NewLendProduct : System.Web.UI.Page
    {
        #region Properties

        private static ProductBiz _productBiz;
        private static ProductBiz ProductManager
        {
            get { return _productBiz ?? (_productBiz = new ProductBiz()); }
        }

        private static WarrantyTicketBiz _warrantyTicketBiz;
        private static WarrantyTicketBiz WarrantyTicketManager
        {
            get { return _warrantyTicketBiz ?? (_warrantyTicketBiz = new WarrantyTicketBiz()); }
        }

        //private static CategoryBiz _categoryBiz;
        //private static CategoryBiz CategoryManager
        //{
        //    get { return _categoryBiz ?? (_categoryBiz = new CategoryBiz()); }
        //}

        private long _ticketId;
        private long TicketId
        {
            get
            {
                if (_ticketId <= 0) long.TryParse(Request.Params["ticketId"], out _ticketId);
                return _ticketId;
            }
        }

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (WarrantyCommon.CurrrentEmployee == null)
            {
                Response.Redirect("~/Logon.aspx");
                return;
            }

            if (!WarrantyCommon.CurrrentEmployee.HasRole(RoleConstant.AdminBaoHanh))
            {
                Response.Redirect("~/NoPermission.aspx");
            }

            if (!IsPostBack)
            {
                if (TicketId <= 0)
                {
                    lblErrorMessage.Text = Resources.GlobalStrings.InstantTicketNotExisted;
                    btnSave.Enabled = false;
                    return;
                }
                LoadData();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            lblErrorMessage.Text = string.Empty;
            errorMessage.Visible = false;

            // validate inputs
            var productId = hidProductId.Value;
            if (string.IsNullOrEmpty(productId))
            {
                lblErrorMessage.Text = Resources.GlobalStrings.LendProductIsRequired;
                errorMessage.Visible = true;
                return;
            }

            var descrition = txtDescription.Text;
            var model = txtModel.Text.Trim();
            var serial = txtSerial.Text.Trim();
            var note = txtNote.Text;

            var ticketProduct = new WarrantyTicket_LendProduct
            {
                WarrantyTicketId = TicketId,
                ProductId = int.Parse(productId),
                Description = descrition,
                Model = model,
                Serial = serial,
                Note = note,
                EmployeeId = int.Parse(ddlEmployees.SelectedValue)
            };

            DateTime lendDate;
            if (DateTime.TryParseExact(txtLendDate.Text.Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out lendDate))
            {
                ticketProduct.LendDate = lendDate;
            }
            else
            {
                errorMessage.Visible = true;
                lblErrorMessage.Text = Resources.GlobalStrings.InvalidDate;
                return;
            }

            int quantity;
            if (int.TryParse(txtQuantity.Text.Trim(), out quantity))
            {
                ticketProduct.Quantity = quantity;
            }

            int manId;
            if (int.TryParse(ddlManufacturers1.SelectedValue, out manId))
            {
                ticketProduct.ManufacturerId = manId;
            }

            if (ddlWarrantyProducts.SelectedIndex > 0)
            {
                ticketProduct.WarrantyProductId = long.Parse(ddlWarrantyProducts.SelectedValue);
            }

            // Call Biz Save Product
            WarrantyTicketManager.CreateTicketLendProduct(ticketProduct);

            Response.Redirect(string.Format("Edit.aspx?id={0}#tabs-2", TicketId));
        }

        #endregion

        #region Helpers

        private void LoadData()
        {
            txtLendDate.Text = string.Format("{0:dd/MM/yyyy}", DateTime.Now);

            // product groups
            var groups = ProductManager.GetAllProductGroups();
            groups.Insert(0, new ProductGroup { Id = 0, Name = Resources.GlobalStrings.AllGroups });
            ddlProductGroups.DataTextField = "Name";
            ddlProductGroups.DataValueField = "Id";
            ddlProductGroups.DataSource = groups;
            ddlProductGroups.DataBind();

            // mans product
            var manufacturers = ProductManager.GetAllManufacturers();
            manufacturers.Insert(0, new Manufacturer { Id = 0, Name = Resources.GlobalStrings.AllManufacturers });
            ddlManufacturers.DataTextField = "Name";
            ddlManufacturers.DataValueField = "Id";
            ddlManufacturers.DataSource = manufacturers;
            ddlManufacturers.DataBind();

            // mans ticket
            manufacturers[0].Name = string.Empty;
            ddlManufacturers1.DataTextField = "Name";
            ddlManufacturers1.DataValueField = "Id";
            ddlManufacturers1.DataSource = manufacturers;
            ddlManufacturers1.DataBind();

            // load employees
            var employees = WarrantyTicketManager.GetEmployees();
            ddlEmployees.DataSource = employees;
            ddlEmployees.DataValueField = "Id";
            ddlEmployees.DataTextField = "Name";
            ddlEmployees.DataBind();

            // load warranty products
            var warrantyProducts = WarrantyTicketManager.GetTicketProducts(TicketId);
            warrantyProducts.Insert(0, new WarrantyTicketProductView { Id = 0, Name = string.Empty });
            ddlWarrantyProducts.DataSource = warrantyProducts;
            ddlWarrantyProducts.DataValueField = "Id";
            ddlWarrantyProducts.DataTextField = "Name";
            ddlWarrantyProducts.DataBind();
        }

        #endregion
    }
}